package com.yigo.cuc.infra.repo;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yigo.cuc.domain.customer.aggregateroot.Customer;
import com.yigo.cuc.domain.customer.repo.CustomerRepo;
import com.yigo.cuc.infra.repo.converter.CustomerDmo2PoConverter;
import com.yigo.cuc.infra.repo.dataobject.CustomerPO;
import com.yigo.cuc.infra.repo.mapper.CustomerMapper;
import com.yigo.framework.http.BException;
import com.yigo.framework.http.RCodeEnum;
import lombok.NonNull;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;

/**
 * @author chenzl
 */
@Repository
public class CustomerRepoImpl implements CustomerRepo {

    @Resource
    private CustomerMapper customerMapper;

    @Override
    public Long countByUserNameOrEmailOrPhone(@NonNull String userName,@NonNull  String email, @NonNull String phone) {
        LambdaQueryWrapper<CustomerPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CustomerPO::getUserName, userName)
                .or().eq(CustomerPO::getEmail, email)
                .or().eq(CustomerPO::getPhone, phone);
        return customerMapper.selectCount(wrapper);
    }

    @Override
    public Customer save(@NonNull Customer dmo) {
        CustomerPO po = CustomerDmo2PoConverter.INSTANCE.toCustomerPO(dmo);
        if (null == po.getId()) {
            if (customerMapper.insert(po) == 0) {
                throw new BException(RCodeEnum.PERSIST_OBJECT_ERROR);
            }
            dmo.setId(po.getId());
        } else {
            if (customerMapper.updateById(po) == 0) {
                throw new BException(RCodeEnum.PERSIST_OBJECT_ERROR);
            }
        }
        return dmo;
    }

    @Override
    public Customer findById(@NonNull Serializable id) {
        CustomerPO po = customerMapper.selectById(id);
        return CustomerDmo2PoConverter.INSTANCE.toDmo(po);
    }
}
